package com.fingard.dsp.bank.directbank.lakala01;

import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.MixFtp;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;

import java.io.File;
import java.text.DecimalFormat;

public class LAKALA01Statement extends LAKALA01Base implements IStatement {
    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();
        String[] tmpSenderUnderHeader = getPosRecStatement(p_reqQrySttm, retAts);
        String tmpSenderUnderTotalNum = retAts.totalNum;
        if (retAts.getWrittenRdCount() == 0) {
            if ("-1".equals(tmpSenderUnderHeader[0])) {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpSenderUnderHeader[1]);
            } else {
                retAts.writeRespCode("0");
                retAts.writeRespInfo("交易为空");
            }
        } else {
            retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(tmpSenderUnderTotalNum)));
        }
        retAts.writeEnd();
        return retAts;
    }

    private String[] getPosRecStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) {
        String[] respHeader = new String[]{"", ""};

        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.totalNum = "0";
        int totalNum = 0;
        String sbFileContent;
        try {
            String dateStr = DateHelper.convertD8toD10(p_reqQrySttm.busDate, "/");

            //文件名称
//            String downFileName = p_reqQrySttm.actNum + "_" + p_reqQrySttm.busDate + ".xls";
            String downFileName = "TF_EX_kaltendin_" + p_reqQrySttm.busDate + ".txt";
            //服务器路径
            String localFilePath = createTempFileDirectory() + File.separator + downFileName;
//            String localFilePath="D:"
            WriteBankLogLn2("拉卡拉交易明细保存本地路径:" + localFilePath);

            //判断本地文件是否存在，不存在则下载，存在则直接读取
            File file = new File(localFilePath);
            if (!file.exists() || file.length() == 0) {
                WriteBankLogLn2("拉卡拉本地路径不存在:" + downFileName + "，前往SFTP服务器下载。");

                FtpSet ftpSet = bankFront.getFtpSet("new_statement");
                WriteBankLogLn2("拉卡拉交易明细SFTP服务器地址:" + ftpSet.serverIP + ":" + ftpSet.port);
                ftpSet.downDir = StringHelper.trimEnd(ftpSet.downDir, "/");
                WriteBankLogLn2("拉卡拉交易明细所在服务器路径:" + ftpSet.downDir + "/"+downFileName);

                FtpReceiver ftpReceiver = null;
//                MixFtp mixFtp = new MixFtp(ftpSet);
//
//                ftpReceiver =  mixFtp.downloadFileFromDir(ftpSet.downDir + File.separator + dateStr +File.separator, downFileName, localFilePath);
                //region SFTP 先注释
//            else if ("sftp".equals(posRecRequestType.toLowerCase())) {
                SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + downFileName;
                WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
                ftpReceiver = sftpPortClient.downloadFile("", sftpFilePath, localFilePath);
//            }
                //endregion
                if (!ftpReceiver.isCompleted) {
                    tmpRespCode = "-1";
                    tmpRespInfo = "拉卡拉交易明细下载失败,原因:" + ftpReceiver.connMsg;
                    retAts.totalNum = String.valueOf(totalNum);
                    respHeader[0] = tmpRespCode;
                    respHeader[1] = tmpRespInfo;
                    return respHeader;
                }
            } else {
                WriteBankLogLn2("拉卡拉本地路径已存在:" + downFileName + "，直接读取本地文件。");
            }
//            sbFileContent = readExcel(localFilePath);
            sbFileContent = FileHelper.readFileText(localFilePath, "UTF-8");
            WriteBankLogLn2("拉卡拉交易明细内容为:\r\n" + sbFileContent);
            String[] totalLine1 = sbFileContent.split("\r\n");
            boolean isContinue = false;
            for (String eachline : totalLine1) {
                String[] eachNode = eachline.split(",");
                //0商户号,1交易日期,2交易时间,3结算时间,4终端号,5网点名称,6交易码,7拉卡拉流水号,8原拉卡拉流水号,
                // 9卡号,10卡类型,11银行,12交易金额,13手续费,14结算金额,15订单号,16系统参考号,17结算状态,18备注
                if (p_reqQrySttm.actNum.equals(eachNode[0].trim())) {
                    totalNum++;
                    isContinue = true;
                    RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                    //终端号
                    tmpRetDetail.termCode = eachNode[4].trim();

                    //交易日期+时间
                    tmpRetDetail.busTime = eachNode[1] + eachNode[2].replace(":", "");
                    if (StringHelper.hasAnyChar(eachNode[9])) {
                        tmpRetDetail.oppAct = eachNode[9].trim();
                    }

                    //业务类型
                    tmpRetDetail.busType = eachNode[6].trim();

                    if (StringHelper.hasAnyChar(eachNode[0])) {
                        tmpRetDetail.askNumber = eachNode[0].trim();
                    }
                    //金额+ 借贷方向
                    if (StringHelper.hasAnyChar(eachNode[12])) {
                        if (eachNode[12].startsWith("-")) {
                            tmpRetDetail.cdFlag = "27";
                        } else {
                            tmpRetDetail.cdFlag = "22";
                        }

                        double amount = Double.parseDouble(eachNode[12].trim().replaceAll("-",""));//交易金额，无小数点精确到分
                        DecimalFormat df = new DecimalFormat();
                        String style = "0.00";
                        df.applyPattern(style);
                        tmpRetDetail.amount = df.format(amount / 100.00);//交易金额

                    }

                    //手续费
                    if (StringHelper.hasAnyChar(eachNode[13])) {
                        double fee = Double.parseDouble(eachNode[13].trim());
                        DecimalFormat df = new DecimalFormat();
                        String style = "0.00";
                        df.applyPattern(style);
                        tmpRetDetail.fee = df.format(fee / 100.00);
                    }

                    //渠道订单号
                    if (StringHelper.hasAnyChar(eachNode[16])) {
                        tmpRetDetail.channelOrderNo = eachNode[16].trim();
                    }
                    tmpRetDetail.transState = TransState.Success;
                    retAts.writeRetDetail(tmpRetDetail);

                }
            }
            if (!isContinue) {
                tmpRespCode = "0";
                tmpRespInfo = "没有符合条件的记录!";
            } else {
                tmpRespCode = "0";
                tmpRespInfo = "获取数据条数：" + totalNum;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {

            retAts.totalNum = String.valueOf(totalNum);

            respHeader[0] = tmpRespCode;
            respHeader[1] = tmpRespInfo;

            return respHeader;
        }
    }

}
